package design.simdi.code.final_paper.site.panels.licente.domenii;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import org.apache.wicket.Component;
import org.apache.wicket.Page;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.wizard.WizardModel;
import org.apache.wicket.extensions.wizard.WizardStep;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import design.simdi.code.final_paper.core.daos.IdeaDao;
import design.simdi.code.final_paper.core.daos.SesiuneDao;
import design.simdi.code.final_paper.core.entities.Bibliography;
import design.simdi.code.final_paper.core.entities.Domain;
import design.simdi.code.final_paper.core.entities.Idea;
import design.simdi.code.final_paper.core.entities.Keyword;
import design.simdi.code.final_paper.core.entities.Person;
import design.simdi.code.final_paper.core.entities.Sesiune;
import design.simdi.code.final_paper.core.entities.User;
import design.simdi.code.final_paper.core.services.ApplicationService;
import design.simdi.code.final_paper.core.services.ServiceException;
import design.simdi.code.final_paper.core.services.UserService;
import design.simdi.code.final_paper.site.application.MyAuthenticatedWebSession;
import design.simdi.code.final_paper.site.application.WicketApplication;
import design.simdi.code.final_paper.site.panels.MyWizard;
import design.simdi.code.final_paper.site.panels.MyWizardButtonBar;

/**
 * 
 * @author Marius Dumitriu - (Jun 24, 2010 - 12:41:09 PM)
 * 
 */
public class AddDomainFromIdeaWizardPanel extends MyWizard {

	private static final long serialVersionUID = 1L;

	private Domain domain;

	private TextField<Integer> totalProiecte;
	private TextArea<String> notes;
	private DropDownChoice<Sesiune> sesiuniComboBox;
	private DropDownChoice<Idea> ideiComboBox;
	private String title;
	private String subtitle;
	@SpringBean
	private ApplicationService applicationService;
	@SpringBean
	private SesiuneDao sesiuneDao;

	@SpringBean
	private IdeaDao ideaDao;

	@SpringBean
	private UserService userService;

	public AddDomainFromIdeaWizardPanel(String id, Domain domain) {
		super(id, false);

		if (domain == null) {
			domain = new Domain();
			title = "form.add.title";
			subtitle = "form.add.subtitle";
		} else {
			title = "form.modify.title";
			subtitle = "form.modify.subtitle";
		}
		this.domain = domain;

		setDefaultModel(new CompoundPropertyModel<AddDomainFromIdeaWizardPanel>(this));
		WizardModel model = new WizardModel();
		model.add(new DomainFromIdeaNameStep());
		model.add(new DomainFromIdeaNotesStep());

		init(model);
		((WicketApplication) getApplication()).setShowErrors(false);
	}

	protected Component newButtonBar(String id) {
		return new MyWizardButtonBar(id, this, getForm()) {

			private static final long serialVersionUID = 1L;

			public void onFinishClick(AjaxRequestTarget target) {

				try {

					onFinish(target);
					DomeniiTabPanel panel = new DomeniiTabPanel("panel");
					panel.setOutputMarkupId(true);

					Page page = this.getPage();

					page.get("content:tabs:panel").replaceWith(panel);

					target.addComponent(page.get("content:tabs:panel"));

				} catch (ServiceException e) {

					error(e.getMessage());
				}

			}

			public void onCancelClick(AjaxRequestTarget target) {
				onCancel(target);
				DomeniiTabPanel panel = new DomeniiTabPanel("panel");
				panel.setOutputMarkupId(true);

				Page page = this.getPage();

				page.get("content:tabs:panel").replaceWith(panel);

				target.addComponent(page.get("content:tabs:panel"));

			}

		};
	}

	public void onFinish(AjaxRequestTarget target) throws ServiceException {

		domain.setAvailableProjectsNo(domain.getTotalProjectsNo());

		domain.setAuthor(getCurrentPerson());
		domain.setCoordonator(getCurrentPerson().getProfesor());
		domain.setSesiune(sesiuniComboBox.getModelObject());

		Idea idee = ideiComboBox.getModelObject();

		idee = ideaDao.get(idee.getId());

		domain.setName(idee.getName());
		domain.setDescription(idee.getDescription());

		if (domain.getKeywords() == null)
			domain.setKeywords(new HashSet<Keyword>());

		for (Keyword key : idee.getKeywords())
			domain.getKeywords().add(key.clone());

		if (domain.getBibliographies() == null)
			domain.setBibliographies(new HashSet<Bibliography>());

		for (Bibliography b : idee.getBibliographies())
			domain.getBibliographies().add(b.clone());

		applicationService.saveDomain(domain);
		onFinishMessage(target);
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setApplicationService(ApplicationService applicationService) {
		this.applicationService = applicationService;
	}

	public ApplicationService getApplicationService() {
		return applicationService;
	}

	public Person getCurrentPerson() {
		User currentUser = ((MyAuthenticatedWebSession) getSession()).getCurrentUser();

		Person p = userService.findPersonByUser(currentUser);
		return p;
	}

	private final class DomainFromIdeaNameStep extends WizardStep {

		private static final long serialVersionUID = 1L;

		public DomainFromIdeaNameStep() {
			super(new ResourceModel(title), new ResourceModel(subtitle));

			add(totalProiecte = new TextField<Integer>("totalProiecte", new PropertyModel<Integer>(domain,
					"totalProjectsNo")));

			List<Sesiune> lista = getSesiuni();

			sesiuniComboBox = new DropDownChoice<Sesiune>("sesiuni-combo", lista);
			sesiuniComboBox.setNullValid(false);
			if (lista.size() > 0)
				for (Sesiune s : lista)
					if (s.isDefaulta())
						sesiuniComboBox.setModel(new Model<Sesiune>(s));
			if (sesiuniComboBox.getModelObject() == null)
				sesiuniComboBox.setModel(new Model<Sesiune>(lista.get(0)));
			sesiuniComboBox.setOutputMarkupId(true);
			add(sesiuniComboBox);

			List<Idea> listaidei = getIdei();

			ideiComboBox = new DropDownChoice<Idea>("idei-combo", listaidei);
			ideiComboBox.setNullValid(false);
			if (listaidei.size() > 0)
				ideiComboBox.setModel(new Model<Idea>(listaidei.get(0)));
			ideiComboBox.setOutputMarkupId(true);
			add(ideiComboBox);

			totalProiecte.setRequired(true);

			totalProiecte.setType(Integer.class);

			if (domain.getId() != null
					&& (domain.getAvailableProjectsNo().intValue() != domain.getTotalProjectsNo().intValue()))
				totalProiecte.setEnabled(false);

		}

	}

	private final class DomainFromIdeaNotesStep extends WizardStep {

		private static final long serialVersionUID = 1L;

		public DomainFromIdeaNotesStep() {
			setTitleModel(new ResourceModel("domainnotes.title"));
			setSummaryModel(new StringResourceModel("domainnotes.summary", this, new Model<Domain>(domain)));

			add(notes = new TextArea<String>("notes", new PropertyModel<String>(domain, "notes")));

			notes.setRequired(false);

			notes.setType(String.class);

		}

	}

	private List<Sesiune> getSesiuni() {
		List<Sesiune> lista = new ArrayList<Sesiune>();
		lista = sesiuneDao.findAll(new Order[] { Order.asc("name") });
		return lista;
	}

	public List<Idea> getIdei() {
		List<Criterion> criterii = new ArrayList<Criterion>();

		criterii.add(Restrictions.eq("person.id", getCurrentPerson().getId()));

		return ideaDao.findAll(new Order[] { Order.asc("name") }, criterii);
	}

	public void setSesiuneDao(SesiuneDao sesiuneDao) {
		this.sesiuneDao = sesiuneDao;
	}

	public SesiuneDao getSesiuneDao() {
		return sesiuneDao;
	}

	public void setIdeaDao(IdeaDao ideaDao) {
		this.ideaDao = ideaDao;
	}

	public IdeaDao getIdeaDao() {
		return ideaDao;
	}

}
